package main

import (
	"fmt"
	"log"
	"react-router/database"
	"react-router/handler"
	"react-router/model"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func setupRoutes(app *fiber.App) {
	apiV1 := app.Group("/api/v1")

	// 配置上传限制
	config := handler.UploadConfig{
		MaxFileSize: 1 << 30, // 10 << 20, // 10MB
		AllowedTypes: map[string]bool{
			"application/pdf":    true,
			"application/msword": true, // .doc
			"application/vnd.openxmlformats-officedocument.wordprocessingml.document": true, // .docx
			"application/vnd.ms-excel": true, // .xls
			"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": true, // .xlsx
			"text/plain":                   true,
			"text/csv":                     true,
			"application/zip":              true,
			"application/x-rar-compressed": true,
		},
	}

	repository := handler.NewGormFileRepository(database.DBConn)
	validator := handler.NewFileValidator(config.MaxFileSize)
	uploadHandler := handler.NewUploadHandler(validator, repository, config.MaxFileSize)
	uploadRoutes := handler.NewUploadRoutes(uploadHandler, repository, config)
	uploadRoutes.SetupRoutes(apiV1)

	app.Get("/file/:id", func(c *fiber.Ctx) error {
		id := c.Params("id")
		file, err := repository.FindByHash(id)
		if err != nil || file == nil {
			return handler.NewErrorResponse(c, model.ERROR_NOT_FOUND)
		}

		c.Set("Content-Type", file.ContentType)
		return c.Send(file.Data)
	})
}

func initDatabase() {
	var err error
	database.DBConn, err = gorm.Open(sqlite.Open("apps.db"))
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println("Connection Opened to Database")

	err = database.DBConn.AutoMigrate(&model.File{})
	if err != nil {
		panic("failed to migrate database: " + err.Error())
	}
	fmt.Println("Database Migrated Successfully")
}

func main() {
	app := fiber.New()
	app.Use(cors.New())

	initDatabase()

	setupRoutes(app)

	log.Fatal(app.Listen(":3000"))
}
